package com.taxsearch.controller.room;

import com.taxsearch.controller.DbbUtil;
import com.taxsearch.dao.NoCredentualsMapper;
import com.taxsearch.dao.QianXianMapper;
import com.taxsearch.dao.room.JingWaiMapper;
import com.taxsearch.dao.room.RoomManagementMapper;
import com.taxsearch.dao.room.RoomSelectMapper;
import com.taxsearch.util.ApiJsonErr;
import com.taxsearch.util.ApiJsonRet;
import com.taxsearch.util.DbUtil;
import com.taxsearch.util.roomutil.RoomUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.*;


/**
 * @description: 房间管理以及两个权限接口
 * @author: 杜一平
 * @create: 2018年8月14日-上午11:57:17
 **/
@Controller
@RequestMapping("/HotelAndroid")
public class RoomManageController {

    /**
     * 总体说明：
     * 参数data为一个json字符串，类似为url地址后面的localhost:8080/HotelAndroid/selectRoom?data
     * ={"status":"1"}中的data 注意调用相关方法解析
     * 返回值为Object,其中返回ApiJsonErr默认状态为400为失败,ApiJsonRet状态为200为成功
     */

    // 日志
    public static final Logger logger = LogManager
            .getLogger(RoomManageController.class);
    // 统一返回结果
    Object result;

    // 房间管理以及其他的dao层
    @Autowired
    private RoomManagementMapper roommanagementmapper;

    // 权限管理dao层
    @Autowired
    private QianXianMapper qianXianMapper;

    // 境外相关操作
    @Autowired
    private JingWaiMapper jingWaiMapper;

    @Autowired
    private NoCredentualsMapper noCredentualsMapper;

    @Autowired
    private RoomSelectMapper roomSelectMapper;


    /**
     * @throws
     * @Title: tuiFang
     * @Description: 退房
     * @param: @param data
     * @param: @return
     * @return: Object
     */
    @RequestMapping("/tuiFang.do")
    @ResponseBody
    public Object tuiFang(String data) {
        // 查询是否有正在无证审批的数据
        Connection connection = DB.getConnection();
        try {
            // 获取相关参数
            Map<String, String> map = RoomUtil.getJsonMap(data);
            // 校验
            if (RoomUtil.validationData(map)) {
                return new ApiJsonErr("有参数为空！");
            }

            String ruzhuid = map.get("ruzhuid");
            String[] ruzhuidStrings = ruzhuid.split(",");
            // 获取批量退房的数据
            List<String> tuiFangbatchList = new LinkedList<>(
                    Arrays.asList(ruzhuidStrings));

//			List<String> wuzhengList=DB.selectWuzhengShenpi(connection, tuiFangbatchList);
            List<String> wuzhengList = roomSelectMapper.selectWuzhengShenpi(tuiFangbatchList);

            // 两个类型都有
            if (wuzhengList.size() != ruzhuidStrings.length && wuzhengList.size() != 0) {
                return new ApiJsonErr("以下人员处于无证审批中：" + wuzhengList + "，请单独操作 !");
            }

            // 都是无证审批
            if (wuzhengList.size() == ruzhuidStrings.length) {
                return new ApiJsonRet("600", "以下人员处于无证审批中：" + wuzhengList + ",只能执行删除操作，是否删除？");
            }

            // 执行批量操作
            roommanagementmapper.tuiFang(tuiFangbatchList);
            // 境外批量退房
            jingWaiMapper.tuiFang(tuiFangbatchList);
            System.out.println("返回成功");
            result = new ApiJsonRet("200", "退房成功！");
        } catch (Exception e) {
            logger.error("tuiFang-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            result = new ApiJsonErr("服务器繁忙,请稍后再试！");
        } finally {
            DB.close(connection);
        }
        return result;
    }

    /**
     * @throws
     * @Title: huanFang
     * @Description: 换房
     * @param: @param data
     * @param: @return
     * @return: Object
     */
    @RequestMapping("/huanFang.do")
    @ResponseBody
    public Object huanFang(String data) {
        // 查询是否有正在无证审批的数据
        Connection connection = DB.getConnection();
        try {
            // 切换数据源为常规数据源
            DbUtil.setDb("1");
            // 获取相关参数
            Map<String, String> map = RoomUtil.getJsonMap(data);
            // 校验
            if (RoomUtil.validationData(map)) {
                return new ApiJsonErr("有参数为空！");
            }

            String ruzhuid = map.get("ruzhuid");
            String newRoom = map.get("newRoom");
            String hotelId = map.get("hotelId");
            String[] ruzhuPeople = ruzhuid.split(",");
            // 获取当前八位系统时间
            String date = RoomUtil.getEightDateNow();
            // 查询预订信息
            List<String> yudingList = roommanagementmapper.selectYuDingXX(
                    hotelId, date);
            // 判断该房间今天是否被预定
            if (yudingList.contains(newRoom)) {
                return new ApiJsonErr("该房间已被预定！");
            }

            // 查询房间号，精确查询最大入住人数
            List<Map<String, String>> roomList = roommanagementmapper
                    .selectRoomJQ(hotelId, newRoom);
            // 获取当天入住人数
            List<Map<String, String>> dangTianRuzhuList = roommanagementmapper
                    .selectRuZhuXXJQ(hotelId, newRoom);
            // 查询境外入住
            List<Map<String, String>> jingwaiRuzhuList = jingWaiMapper
                    .selectJingWai(hotelId, newRoom);

            List<String> ruzhuList = new LinkedList<>(
                    Arrays.asList(ruzhuPeople));


            List<String> wuzhengList = DB.selectWuzhengShenpi(connection, ruzhuList);
            if (wuzhengList.size() > 0) {
                return new ApiJsonErr("以下人员处于无证审批中：" + wuzhengList + " !");
            }

//			System.out.println("换房认证");
//			// 有人认证比对失败就封禁操作
//			for(Map<String, String>map2:dangTianRuzhuList){
//				System.out.println("开始"+map2.get("DJ_XINGMING")+map2.get("DJ_XINGMING"));
//				if(map2.get("ENTERPRISE_ID").equals("5")){
//					return new ApiJsonErr("以下人员认证比对失败："+map2.get("DJ_XINGMING")+" !");
//				}
//			}

            if (ruzhuList.size() != 0 && roomList.size() != 0) {

                Map<String, String> mm = roomList.get(0);
                // 发现一个很奇葩的东西
                // System.out.println("最大人数"+mm.get("maxpeople"));
                JSONObject json = (JSONObject) JSONObject.toJSON(mm);
                // 换房人数是否超限
                if (ruzhuList.size() > (Integer.parseInt(json
                        .getString("maxpeople")) - dangTianRuzhuList.size() - jingwaiRuzhuList.size())) {
                    result = new ApiJsonErr("换房失败，换房人数超过目标房间可住人数！");
                } else {
                    // 执行批量操作
                    roommanagementmapper.huanFang(ruzhuList, newRoom);
                    // 境外批量换房
                    jingWaiMapper.huanFang(ruzhuList, newRoom);
                    result = new ApiJsonRet("200", "换房成功！");
                }
            } else {
                result = new ApiJsonErr("请输入正确的房间号！");
            }
        } catch (Exception e) {
            logger.error("huanFang-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            result = new ApiJsonErr("服务器繁忙,请稍后再试！");
        } finally {
            DB.close(connection);
        }
        System.out.println("返回成功");
        return result;
    }

    /**
     * @throws
     * @Title: deleteWuXiaoRuzhu
     * @Description: 删除无效入住信息
     * @param: @param data
     * @param: @return
     * @return: Object
     */
    @RequestMapping("/deleteWuXiaoRuzhu.do")
    @ResponseBody
    public Object deleteWuXiaoRuzhu(String data) {
        try {
            // 切换数据源为常规数据源
            DbUtil.setDb("1");
            // 获取相关参数
            Map<String, String> map = RoomUtil.getJsonMap(data);
            // 校验
            if (RoomUtil.validationData(map)) {
                return new ApiJsonErr("有参数为空！");
            }
            String ruzhuid = map.get("ruzhuid");
            String[] ruzhuPeople = ruzhuid.split(",");
            List<String> ruzhuList = new LinkedList<>(
                    Arrays.asList(ruzhuPeople));

            // 备份原有入住数据
            roommanagementmapper.insertCopy(ruzhuList);

            // 执行删除
            roommanagementmapper.deleteWuXiaoRuzhu(ruzhuList);
            result = new ApiJsonRet("200", "删除无效入住信息成功！");
        } catch (Exception e) {
            logger.error("deleteWuXiaoRuzhu-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            result = new ApiJsonErr("服务器繁忙,请稍后再试！");
        }
        System.out.println("返回成功");
        return result;
    }


    /**
     * @throws
     * @Title: deleteWuXiaoRuzhu
     * @Description: 刷新无证
     * @param: @param data
     * @param: @return
     * @return: Object
     */
    @RequestMapping("/shuaXinWuZheng.do")
    @ResponseBody
    public Object shuaXinWuZheng(String data) {
        try {
            DbUtil.setDb("3");

            // 获取入住JDBC
            Connection gongAnDB = GongAnDB.getConnection();

            Map<String, String> map = RoomUtil.getJsonMap(data);
            String hotelId = map.get("hotelId");
            String roomNum = map.get("roomNum");
            //先更新
            //1.将ENTERPRISE_ID=0 但审批成功的 变为1 并且将入住表中BUPLOAD变为1
            //查询审批成功的RECORDSNO
            List<HashMap<String, String>> listID = noCredentualsMapper.getNoCredentialsOk(hotelId);
            System.out.println("成功" + listID);
            if (listID.size() > 0) {
                //修改无证审批表ENTERPRISE_ID 0-1
                noCredentualsMapper.updateNoCredentialsOk(hotelId, listID);
                //修改入住表BUPLOAD -》 1  JDBC
                Connection connection = DbbUtil.getConnection();

                // 修改入住状态为无证审批成功
                List<String> ids = getId(listID);
                GongAnDB.updateRuzhuStatus(gongAnDB, ids, "2");

                try {
                    DbbUtil.updateCheckInBUPLOAD(connection, hotelId, listID);
                } catch (SQLException e) {
                    e.printStackTrace();
                } finally {
                    DbbUtil.close(connection);
                }
            }
            // 获取无证审批失败的旅客
            List<String> shiBaiList = roomSelectMapper.selectWuZhengShiBai(hotelId);
            System.out.println("1111" + shiBaiList);
            //2.将ENTERPRISE_ID=0 但审批失败的 变为2 入住表中BUPLOAD不改变
            noCredentualsMapper.updateNoCredentialsNo(hotelId);

            // 用JDBC更新入住表无证审批状态为审批失败，可能为机器审批失败，也可能为时间超过限制
            GongAnDB.updateRuzhuStatus(gongAnDB, shiBaiList, "3");
            // 查询入住表那些数据需要更新
            List<Map<String, String>> list = GongAnDB.selectWuzhengFromRuzhu(gongAnDB, hotelId);
            GongAnDB.close();

            Map<String, Object> map2 = new HashMap<>();
            // 整合数据
            getData(map2, list, roomNum);

            result = new ApiJsonRet("200", map2);
            DbUtil.setDb("1");
        } catch (Exception e) {
            logger.error("deleteWuXiaoRuzhu-发生错误!!!!!!!!!!!!!!!!!!!!!!!!", e);
            result = new ApiJsonErr("服务器繁忙,请稍后再试！");
        }
        System.out.println("返回成功");
        return result;
    }

    /**
     * @throws
     * @Title: getData
     * @Description: 整合前端需要的数据
     * @param: @param map2
     * @param: @param list 需要有感叹号的房间
     * @param: @param roomNum 房间号
     * @return: void
     */
    public void getData(Map<String, Object> map2, List<Map<String, String>> list, String roomNum) {
        // 运用set去重
        Set<String> set = new HashSet<>();
        String msg = "";
        for (Map<String, String> map : list) {
            // 如果旅客入住状态为在审核或者审核失败则有感叹号
            if ("0".equals(map.get("ENTERPRISE_ID")) || "3".equals(map.get("ENTERPRISE_ID"))
                    || "5".equals(map.get("ENTERPRISE_ID"))) {
                set.add(map.get("DJ_RUZHUFANGHAO"));
            }
            // 去掉人证比对成功状态
            if (!"4".equals(map.get("ENTERPRISE_ID"))) {
                if (roomNum.equals(map.get("DJ_RUZHUFANGHAO"))) {
                    msg += map.get("DJ_XINGMING") + ":" + getTiShi(map.get("ENTERPRISE_ID")) + ";";
                }
            }

        }
        map2.put("wenHaoNumList", set);
        map2.put("msg", msg);
    }


    public static String getTiShi(String s) {
        if ("0".equals(s)) {
            return "无证审核中";
        }
        if ("2".equals(s)) {
            return "无证审核成功";
        }
        if ("3".equals(s)) {
            return "无证审核失败";
        }
        if ("4".equals(s)) {
            return "人证比对成功";
        }
        if ("5".equals(s)) {
            return "人证比对失败";
        }
        return "未知状态";
    }

    // 剔除多余元素,只留下id
    public List<String> getId(List<HashMap<String, String>> listID) {
        List<String> idsList = new LinkedList<>();
        for (HashMap<String, String> m : listID) {
            idsList.add(m.get("ID"));
        }
        return idsList;
    }
}
